package org.theonept.travian.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.theonept.travian.model.Compte;

public class ConnexionUtil extends HttpUtil {

	public static Compte connect(Compte compte) {
		try {
			CookieManager cookieManager = new CookieManager();
			CookieHandler.setDefault(cookieManager);
			URL urlFirst = new URL(compte.getUrlServeur());
			HttpURLConnection connectionFirst = (HttpURLConnection) urlFirst
					.openConnection();
			Document first = Jsoup.parse(connectionFirst.getInputStream(),
					connectionFirst.getContentEncoding(),
					compte.getUrlServeur());
			String login = first.getElementsByAttributeValue("name", "login")
					.get(1).attr("value");

			StringBuilder sbString = new StringBuilder();

			sbString.append("name=");
			sbString.append(URLEncoder.encode(compte.getUsername(), "UTF-8"));
			sbString.append("&password=");
			sbString.append(URLEncoder.encode(compte.getPassword(), "UTF-8"));
			sbString.append("&w=");
			sbString.append(URLEncoder.encode("1680-1050", "UTF-8"));
			sbString.append("&login=");
			sbString.append(URLEncoder.encode(login, "UTF-8"));

			String result = excutePost(compte.getUrlServeur() + "dorf1.php",
					sbString.toString());
			if (result.contains("accountNameOrEmailAddress")) {
				compte.setEtat(false);
				return compte;
			}
			Compte.parseCompte(result, compte);
			compte.setEtat(true);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return compte;
	}

	public static void disconnect(Compte compte) {
		try {
			URL url = new URL(compte.getUrlServeur() + "logout.php");
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();

			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuffer response = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			connection.disconnect();
		} catch (Exception e) {

		}

	}
}
